<?php


/**
 * 获取当前域名
 */
function _domain()
{
    return str_replace('https://', '', str_replace('http://', '', url('/')));
}

/**
 * 数组转xml
 */
function arrayToXml($array)
{
    $xml = '<xml>';
    forEach ($array as $k => $v) {
        $xml .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . '>';
    }
    $xml .= '</xml>';
    return $xml;
}

/**
 * 签名生成
 */
function _sign($params, $key)
{
    $signPars = "";
    ksort($params);
    foreach ($params as $k => $v) {
        if ("" != $v && "sign" != $k) {
            $signPars .= $k . "=" . $v . "&";
        }
    }
    $signPars .= "key=" . $key;
    return md5($signPars);
}

/**
 * 普通对称校验签名
 */
function get_sign($params)
{
    $url = arr_to_url($params, false);
    $url = $url . '&key=' . env('SECRET_KEY');
    // v('get_zw_notify_sign_url:'.$url);
    $sign = md5($url);
    return $sign;
}

function arr_to_url($array, $has_sign = false)
{
    ksort($array);
    reset($array);
    $arg = "";
    while (list ($name, $val) = each($array)) {
        if ($name == 'sign' && !$has_sign) continue;
        if (strpos($name, "_") === 0)
            continue;
        if (is_array($val))
            $val = join(',', $val);
        if ($val === "")
            continue;
        $arg .= $name . "=" . $val . "&";
    }
    $arg = substr($arg, 0, count($arg) - 2);

    return $arg;
}

/**
 * 获取真实IP
 */
function _getIp()
{
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARD_FOR") && strcasecmp(getenv("HTTP_X_FORWARD_FOR"), "unknown"))
        $ip = getenv("HTTP_X_FORWARD_FOR");
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = "unknown";
    return ($ip);
}

/**
 * 数组 转 对象
 * @param array $arr 数组
 * @return object
 */
function array_to_object($arr)
{
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }
    return (object)$arr;
}

/**
 * 对象 转 数组
 * @param object $obj 对象
 * @return array
 */
function object_to_array($obj)
{
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
    return $obj;
}

/**
 * 检查是否为手机号码
 */
function _isPhone($number)
{
    return preg_match("/^1[34578][0-9]{9}$/", $number);
}

/**
 * 获取渠道域名
 */
function get_channel_domain($distribution_channel_id)
{
    return env('PROTOCOL') . '://' . env('CHANNEL_SITE_PREFIX') . "{$distribution_channel_id}." . env('CHANNEL_MAIN_DOMAIN');
}

/**
 * 判断所传的参数是否缺少,如果缺少返回渠道的字段，正确返回0
 * @param array $param
 * @param array $must
 * @return int|mixed
 */
function checkParam(Array $param, Array $must)
{
    foreach ($must as $item) {
        if (array_key_exists($item, $param) && $param[$item] != '') {

        } else {
            return $item;
        }
    }
    return 0;
}

/**
 * 获取省份城市列表
 */
function _cities()
{
    $cities_json = '{"北京市":["北京市"],"天津市":["天津市"],"河北省":["石家庄市","唐山市","秦皇岛市","邯郸市","邢台市","保定市","张家口市","承德市","沧州市","廊坊市","衡水市"],"山西省":["太原市","大同市","阳泉市","长治市","晋城市","朔州市","晋中市","运城市","忻州市","临汾市","吕梁市"],"内蒙古自治区":["呼和浩特市","包头市","乌海市","赤峰市","通辽市","鄂尔多斯市","呼伦贝尔市","巴彦淖尔市","乌兰察布市","兴安盟","锡林郭勒盟","阿拉善盟"],"辽宁省":["沈阳市","大连市","鞍山市","抚顺市","本溪市","丹东市","锦州市","营口市","阜新市","辽阳市","盘锦市","铁岭市","朝阳市","葫芦岛市"],"吉林省":["长春市","吉林市","四平市","辽源市","通化市","白山市","松原市","白城市","延边朝鲜族自治州"],"黑龙江省":["哈尔滨市","齐齐哈尔市","鸡西市","鹤岗市","双鸭山市","大庆市","伊春市","佳木斯市","七台河市","牡丹江市","黑河市","绥化市","大兴安岭地区"],"上海市":["上海市"],"江苏省":["南京市","无锡市","徐州市","常州市","苏州市","南通市","连云港市","淮安市","盐城市","扬州市","镇江市","泰州市","宿迁市"],"浙江省":["杭州市","宁波市","温州市","嘉兴市","湖州市","绍兴市","金华市","衢州市","舟山市","台州市","丽水市"],"安徽省":["合肥市","芜湖市","蚌埠市","淮南市","马鞍山市","淮北市","铜陵市","安庆市","黄山市","滁州市","阜阳市","宿州市","六安市","亳州市","池州市","宣城市"],"福建省":["福州市","厦门市","莆田市","三明市","泉州市","漳州市","南平市","龙岩市","宁德市"],"江西省":["南昌市","景德镇市","萍乡市","九江市","新余市","鹰潭市","赣州市","吉安市","宜春市","抚州市","上饶市"],"山东省":["济南市","青岛市","淄博市","枣庄市","东营市","烟台市","潍坊市","济宁市","泰安市","威海市","日照市","莱芜市","临沂市","德州市","聊城市","滨州市","菏泽市"],"河南省":["郑州市","开封市","洛阳市","平顶山市","安阳市","鹤壁市","新乡市","焦作市","濮阳市","许昌市","漯河市","三门峡市","南阳市","商丘市","信阳市","周口市","驻马店市"],"湖北省":["武汉市","黄石市","十堰市","宜昌市","襄阳市","鄂州市","荆门市","孝感市","荆州市","黄冈市","咸宁市","随州市","恩施土家族苗族自治州"],"湖南省":["长沙市","株洲市","湘潭市","衡阳市","邵阳市","岳阳市","常德市","张家界市","益阳市","郴州市","永州市","怀化市","娄底市","湘西土家族苗族自治州"],"广东省":["广州市","韶关市","深圳市","珠海市","汕头市","佛山市","江门市","湛江市","茂名市","肇庆市","惠州市","梅州市","汕尾市","河源市","阳江市","清远市","东莞市","中山市","潮州市","揭阳市","云浮市"],"广西壮族自治区":["南宁市","柳州市","桂林市","梧州市","北海市","防城港市","钦州市","贵港市","玉林市","百色市","贺州市","河池市","来宾市","崇左市"],"海南省":["海口市","三亚市","三沙市","儋州市"],"重庆市":["重庆市"],"四川省":["成都市","自贡市","攀枝花市","泸州市","德阳市","绵阳市","广元市","遂宁市","内江市","乐山市","南充市","眉山市","宜宾市","广安市","达州市","雅安市","巴中市","资阳市","阿坝藏族羌族自治州","甘孜藏族自治州","凉山彝族自治州"],"贵州省":["贵阳市","六盘水市","遵义市","安顺市","毕节市","铜仁市","黔西南布依族苗族自治州","黔东南苗族侗族自治州","黔南布依族苗族自治州"],"云南省":["昆明市","曲靖市","玉溪市","保山市","昭通市","丽江市","普洱市","临沧市","楚雄彝族自治州","红河哈尼族彝族自治州","文山壮族苗族自治州","西双版纳傣族自治州","大理白族自治州","德宏傣族景颇族自治州","怒江傈僳族自治州","迪庆藏族自治州"],"西藏自治区":["拉萨市","日喀则市","昌都市","林芝市","山南市","那曲地区","阿里地区"],"陕西省":["西安市","铜川市","宝鸡市","咸阳市","渭南市","延安市","汉中市","榆林市","安康市","商洛市"],"甘肃省":["兰州市","嘉峪关市","金昌市","白银市","天水市","武威市","张掖市","平凉市","酒泉市","庆阳市","定西市","陇南市","临夏回族自治州","甘南藏族自治州"],"青海省":["西宁市","海东市","海北藏族自治州","黄南藏族自治州","海南藏族自治州","果洛藏族自治州","玉树藏族自治州","海西蒙古族藏族自治州"],"宁夏回族自治区":["银川市","石嘴山市","吴忠市","固原市","中卫市"],"新疆维吾尔自治区":["乌鲁木齐市","克拉玛依市","吐鲁番市","哈密市","昌吉回族自治州","博尔塔拉蒙古自治州","巴音郭楞蒙古自治州","阿克苏地区","克孜勒苏柯尔克孜自治州","喀什地区","和田地区","伊犁哈萨克自治州","塔城地区","阿勒泰地区"],"台湾省":[],"香港特别行政区":[],"澳门特别行政区":[]}';
    return json_decode($cities_json, 1);
}

/**
 * 对象 转 数组
 * @param object $obj 对象
 * @return array
 */
function ignoreKeyInArray($targetArray, $delete_keys = [], $changes = [])
{
    $change_keys = array_keys($changes);
    foreach ($targetArray as $key => $value) {
        if (in_array($key, $delete_keys) && isset($targetArray[$key])) unset($targetArray[$key]);
        if (in_array($key, $change_keys) && isset($targetArray[$key])) $targetArray[$key] = $changes[$key];
        if (is_array($value)) ignoreKeyInArray($value, $delete_keys, $change_keys);
    }
    return $targetArray;
}

function itemTransform($trans, $data)
{
    if ($data) {
        return $trans->transform($data);
    } else {
        return [];
    }
}

function collectionTransform($trans, $data)
{
    $ret_data = [];
    if ($data) {
        foreach ($data as $item) {
            $ret_data[] = $trans->transform($item);
        }
    }
    return $ret_data;
}


function ImageNewsToArray($datas)
{
    if (empty($datas)) return null;
    if (!is_array($datas)) {
        $datas = json_decode($datas);
    }
    $send_data = array();
    foreach ($datas as $no => $data) {
        foreach ($data as $_data) {
            foreach ($_data as $key => $one_data) {
                $send_data[$no][$key] = $one_data;
            }
        }
    }
    return $send_data;
}

/**
 * 加密site id
 */
function encodeDistributionChannelId($id)
{
    $hashids = new \Hashids\Hashids('out_zhuishuyun', 16);
    return $hashids->encode($id);
}

/**
 * 解密密site id
 */
function decodeDistributionChannelId($code)
{
    $hashids = new \Hashids\Hashids('out_zhuishuyun', 16);
    $res = $hashids->decode($code);
    if ($res && isset($res[0])) {
        return $res[0];
    }
    return null;
}

//bid加密
function book_hash_encode($bid)
{
    return Vinkla\Hashids\Facades\Hashids::encode($bid);
}

//bid解密
function book_hash_decode($encrypt_bid)
{
    return Vinkla\Hashids\Facades\Hashids::decode($encrypt_bid);
}

/**
 * 保存Excel格式数据表 需要composer require phpoffice/phpspreadsheet
 * @param $header
 * @param $data
 * @param $path eg. storage_path('app/excel.xlsx')
 * @param $remark array $remark['cell']备注单元格 ￥remark['contents']备注内容
 */
function saveExcelData($header, $data, $path, $remark = '', $fileName = '')
{

    $objPHPExcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    // Set document properties
    // Rename worksheet
    $objPHPExcel->getActiveSheet()->setTitle('Phpmarker-' . date('Y-m-d'));
    // Set active sheet index to the first sheet, so Excel opens this as the first sheet
    $objPHPExcel->setActiveSheetIndex(0);
    //设置header
    if (!is_array($header)) {
        return false;
    }
    $ini = 65;//A的acsii码
    foreach ($header as $value) {
        $objPHPExcel->getActiveSheet()->getColumnDimension(chr($ini))->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->setCellValue(chr($ini++) . '1', $value);
    }
    if (!is_array($data)) {
        return false;
    }
    $i = 2;

    foreach ($data as $val) {
        $ini = 65;
        foreach ($val as $item) {
            $objPHPExcel->getActiveSheet()->setCellValue(chr($ini++) . $i, $item);
        }
        ++$i;
    }
    if ($remark) {
        $conditional1 = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
        $conditional1->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS)
            ->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_BETWEEN)
            ->addCondition('200')
            ->addCondition('400');
        $conditional1->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_YELLOW);

        foreach ($remark as $key => $value) {
            $conditionalStyles = $objPHPExcel->getActiveSheet()->getStyle($value['cell'])->getConditionalStyles();
            $conditionalStyles[] = $conditional1;
            $objPHPExcel->getActiveSheet()->getStyle($value['cell'])->setConditionalStyles($conditionalStyles);
            $objPHPExcel->getActiveSheet()->setCellValue($value['cell'], $value['contents']);
        }
    }
    if (!$path) {
        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        if (!$fileName) {
            $fileName = '01simple';
        }
        header('Content-Disposition: attachment;filename=' . $fileName . ".xlsx");
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $writer->save('php://output');
        //return true;
    } else {
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $writer->save($path);
    }
}

function saveExcelDataToMultiSheet(Array $param, $path)
{
    $sheet_num = count($param);
    //\Log::info($sheet_num);
    //\Log::info($param);
    $objPHPExcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $new_sheet = null;
    for ($j = 0; $j < $sheet_num; $j++) {
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        if ($j > 0) {
            \Log::info('created_sheet');
            $objPHPExcel->createSheet($j);
            //\Log::info($new_sheet);
        }
        $objPHPExcel->setActiveSheetIndex($j);
        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle($param[$j]['title']);

        //设置header
        if (!is_array($param[$j]['header'])) {
            return false;
        }
        $header = $param[$j]['header'];
        $ini = 65;//A的acsii码
        foreach ($header as $value) {
            $objPHPExcel->getActiveSheet()->setCellValue(chr($ini++) . '1', $value);
        }
        if (!is_array($param[$j]['data'])) {
            return false;
        }
        $data = $param[$j]['data'];
        $i = 2;

        foreach ($data as $val) {
            $ini = 65;
            foreach ($val as $item) {
                $objPHPExcel->getActiveSheet()->setCellValue(chr($ini++) . $i, $item);
            }
            ++$i;
        }
    }
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xlsx');
    $writer->save($path);
}

function myLog($name, $filename = '')
{
    if (!$filename) {
        $filename = $name;
    }
    $filename = $filename . '.log';
    $logger = new \Monolog\Logger(storage_path('logs/' . $filename));
    $writer = new \Illuminate\Log\Writer($logger);
    $writer->useDailyFiles(storage_path('logs/' . $filename));
    return $writer;
}

/**
 * 从域名中解析渠道id 只能用H5
 * @param \Illuminate\Http\Request $request
 * @return mixed
 */
function getDistributionChannelId(\Illuminate\Http\Request $request)
{
    $route = $request->route();
    $parameters = $route->parameters();
    $parameterNames = $route->parameterNames();
    $distribution_channel_id = $parameters[$parameterNames[0]];
    return $distribution_channel_id;
}